<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import api from '@/utils/api'
import Toast from '@/components/Toast.vue'
import { showToast } from '@/utils/toast'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'

const router = useRouter()
const chartRef = ref(null) // 收支趋势图表引用
let chart = null // 收支趋势图表实例

const budgetChartRef = ref(null) // 预算图表引用
let budgetChart = null // 预算图表实例

// 用户信息
const username = ref('') // 用户名

// 收支统计
const income = ref(0) // 收入总额
const expense = ref(0) // 支出总额

// 预算统计
const totalBudget = ref(0) // 总预算金额
const totalActualExpense = ref(0) // 实际支出金额

// 账单列表
const bills = ref([]) // 存储账单列表数据
const loading = ref(false) // 加载状态标识

// 图表数据
const chartData = ref({
  dates: [], // 日期数组
  income: [], // 收入数据数组
  expense: [] // 支出数据数组
})

// 添加账单弹窗相关
const showAddModal = ref(false) // 控制添加账单弹窗显示
const isEditing = ref(false) // 是否为编辑模式
const newBill = ref({
  bill_type: '', // 账单类型
  amount: '', // 金额
  type: '0', // 类型：0-支出，1-收入
  payment_status: 0, // 支付状态：0-未支付，1-已支付
  payment_method: '', // 支付方式
  due_date: new Date().toISOString().split('T')[0], // 记录日期，默认今天
  description: '' // 备注说明
})

// 预算类型选项
const budgetCategories = [
  { value: '房租', label: '房租' },
  { value: '交通', label: '交通' },
  { value: '伙食', label: '伙食' },
  { value: '购物', label: '购物' },
  { value: '娱乐', label: '娱乐' },
  { value: '教育', label: '教育' },
  { value: '医疗', label: '医疗' },
  { value: '其他', label: '其他' }
]

// 收入类型选项
const incomeCategories = [
  { value: '工资', label: '工资' },
  { value: '奖金', label: '奖金' },
  { value: '投资收益', label: '投资收益' },
  { value: '兼职收入', label: '兼职收入' },
  { value: '礼金', label: '礼金' },
  { value: '退款', label: '退款' },
  { value: '其他', label: '其他' }
]

// 账单类型相关
const showCustomType = ref(false) // 控制自定义类型输入框显示
const customType = ref('') // 自定义类型值

// 获取用户信息
const getUserInfo = async () => {
  try {
    const response = await api.get('/api/get_user_info')
    if (response.data.code === 0) {
      username.value = response.data.data.username.username
    }
  } catch (error) {
    showToast('获取用户信息失败', 'error')
  }
}

// 获取收支统计
const getStatistics = async () => {
  try {
    const response = await api.get('/api/get_statistics')
    if (response.data.code === 0) {
      income.value = response.data.data.income || 0
      expense.value = response.data.data.expense || 0
    }
  } catch (error) {
    showToast('获取收支统计失败', 'error')
  }
}

// 获取预算列表
const getBudgets = async () => {
  try {
    const response = await api.get('/api/get_budgets')
    if (response.data.code === 0) {
      const budgets = response.data.data || []
      totalBudget.value = budgets.reduce((sum, budget) => sum + budget.amount, 0)
      totalActualExpense.value = budgets.reduce((sum, budget) => sum + (budget.actual_expense || 0), 0)
      
      // 检查实际支出是否超过总预算
      if (totalActualExpense.value > totalBudget.value) {
        const overBudget = totalActualExpense.value - totalBudget.value
        showToast(`本月当前支出已超出总预算的${(overBudget / totalBudget.value * 100).toFixed(2)}%，合计是${overBudget.toFixed(2)}元`, 'error')
      }
    }
  } catch (error) {
    showToast('获取预算列表失败', 'error')
  }
}

// 获取最近账单
const getRecentBills = async () => {
  loading.value = true
  try {
    const response = await api.get('/api/get_bills', {
      params: {
        current_page: 1,
        page_size: 9999
      }
    })
    if (response.data.code === 0) {
      bills.value = response.data.data || [];
      
      // 按创建日期倒序排序
      bills.value.sort((a, b) => {
        const dateA = new Date(a.created_date.replace(/-/g, '/'));
        const dateB = new Date(b.created_date.replace(/-/g, '/'));
        return dateB - dateA; // 降序排序
      });

      // 只保留最新的 3 个账单
      bills.value = bills.value.slice(0, 3);
    }
  } catch (error) {
    showToast('获取账单记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 获取图表数据
const getChartData = async () => {
  try {
    const response = await api.get('/api/get_chart_data')
    if (response.data.code === 0) {
      // 反转数组，使时间从左到右递增
      const data = response.data.data
      chartData.value = {
        dates: data.dates.reverse(),
        income: data.income.reverse(),
        expense: data.expense.reverse()
      }
      initChart()
    }
  } catch (error) {
    showToast('获取图表数据失败', 'error')
  }
}

// 初始化收支趋势图表
const initChart = () => {
  if (chart) {
    chart.dispose()
  }
  
  chart = echarts.init(chartRef.value)
  
  const option = {
    title: {
      text: '收支趋势',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['收入', '支出'],
      bottom: 0,
      selectedMode: true  // 允许切换显示/隐藏
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.dates,
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '金额'
    },
    series: [
      {
        name: '收入',
        type: 'line',
        data: chartData.value.income,
        itemStyle: {
          color: '#67c23a'
        },
        smooth: true,
        emphasis: {
          focus: 'series'
        }
      },
      {
        name: '支出',
        type: 'line',
        data: chartData.value.expense,
        itemStyle: {
          color: '#f56c6c'
        },
        smooth: true,
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化预算图表
const initBudgetChart = () => {
  if (budgetChart) {
    budgetChart.dispose()
  }
  
  budgetChart = echarts.init(budgetChartRef.value)
  
  const option = {
    title: {
      text: '预算使用情况',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: 0
    },
    series: [
      {
        name: '预算',
        type: 'pie',
        radius: '50%',
        data: [
          { value: totalBudget.value, name: '总预算' },
          { value: totalActualExpense.value, name: '实际支出' }
        ],
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  budgetChart.setOption(option)
  
  window.addEventListener('resize', () => {
    budgetChart.resize()
  })
}

// 跳转到添加账单页面
const goToAddBill = () => {
  router.push('/bill')
}

// 跳转到账单详情页面
const goToBillDetail = (id) => {
  router.push('/bill')
}

// 格式化金额
const formatAmount = (amount) => {
  return amount.toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 验证表单数据
const validateForm = () => {
  if (!newBill.value.bill_type.trim()) {
    showToast('请输入账单类型', 'error')
    return false
  }
  
  if (!newBill.value.amount || parseFloat(newBill.value.amount) <= 0) {
    showToast('请输入有效的金额', 'error')
    return false
  }
  
  return true
}

// 监听账单类型变化
watch(() => newBill.value.bill_type, (newValue) => {
  showCustomType.value = newValue === 'other'
  if (newValue !== 'other') {
    customType.value = ''
  }
})

// 监听自定义类型变化
watch(() => customType.value, (newValue) => {
  if (showCustomType.value) {
    newBill.value.bill_type = newValue
  }
})

// 监听支付类型变化
watch(() => newBill.value.type, (newType) => {
  if (newType === '1') {
    newBill.value.payment_status = -1
    newBill.value.bill_type = ''  // 重置账单类型
    showCustomType.value = false
    customType.value = ''
  }
  else {
    newBill.value.payment_status = 0
    newBill.value.bill_type = ''  // 重置账单类型
    showCustomType.value = false
    customType.value = ''
  }
})

// 重置账单表单
const resetForm = () => {
  newBill.value = {
    bill_type: '',
    amount: '',
    type: '0',
    payment_status: 0,
    payment_method: '',
    due_date: new Date().toISOString().split('T')[0], // 默认选今天的日期
    description: ''
  }
  showCustomType.value = false
  customType.value = ''
}

// 添加账单
const handleAddBill = async () => {
  if (!validateForm()) {
    return
  }

  try {
    const response = await api.post('/api/add_bill', newBill.value)
    if (response.data.code === 0) {
      showToast('添加成功', 'success')
      showAddModal.value = false
      await Promise.all([
        getRecentBills(),
        getStatistics(),
        getBudgets(),
        getChartData()
      ])
      resetForm()
    } else {
      showToast(response.data.message, 'error')
    }
  } catch (error) {
    showToast('添加失败', 'error')
  }
}

// 当点击添加账单按钮时
const handleAddClick = () => {
  resetForm()
  isEditing.value = false
  showAddModal.value = true
}

// 检查新消息
const checkNewMessages = async () => {
  try {
    const response = await api.get('/api/check_new_messages')
    if (response.data.code === 0 && response.data.newMessages) {
      showToast('您有新消息！请前往系统通知查看', 'success')
    }
    if (response.data.code === 1) {
      showToast('您有新消息！请前往系统通知查看', 'success')
    }
  } catch (error) {
    showToast('检查新消息失败', 'error')
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await getUserInfo()
  await getStatistics()
  await getBudgets()
  await getRecentBills()
  await getChartData()
  initChart()
  initBudgetChart()
  await checkNewMessages()
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
  if (budgetChart) {
    budgetChart.dispose()
  }
})
</script>

<template>
  <div class="page-wrapper">
    <div class="page-container">
      <div class="home-container">
        <Toast />
        
        <!-- 用户信息卡片 -->
        <div class="user-card">
          <div class="user-info">
            <h2>欢迎回来，{{ username }}</h2>
          </div>
        </div>

        <!-- 收支统计卡片 -->
        <div class="statistics-card">
          <div class="stat-item income">
            <div class="label">本月收入</div>
            <div class="amount">¥{{ formatAmount(income) }}</div>
          </div>
          <div class="stat-item expense">
            <div class="label">本月支出</div>
            <div class="amount">¥{{ formatAmount(expense) }}</div>
          </div>
        </div>

        <!-- 快速操作区 -->
        <div class="quick-actions">
          <button class="action-btn add-bill" @click="handleAddClick">
            <i class="icon">+</i>
            <span>记一笔</span>
          </button>
        </div>

        <!-- 最近账单 -->
        <div class="recent-bills">
          <div class="section-header">
            <h3>最近账单</h3>
            <router-link to="/bill" class="view-all">查看全部</router-link>
          </div>
          
          <div v-if="loading" class="loading">加载中...</div>
          <div v-else-if="bills.length === 0" class="empty">暂无账单记录</div>
          <div v-else class="bill-list">
            <div 
              v-for="bill in bills" 
              :key="bill.bill_id" 
              class="bill-item"
              @click="goToBillDetail(bill.bill_id)"
            >
              <div class="bill-info">
                <div class="category">{{ bill.bill_type }}</div>
                <div class="date">{{ bill.created_date }}</div>
              </div>
              <div class="amount" :class="{ 'income': bill.type === 1, 'expense': bill.type === 0 }">
                {{ bill.type === 1 ? '+' : '-' }}¥{{ formatAmount(bill.amount) }}
              </div>
            </div>
            <div v-if="bills.length < 3" class="no-more">
              暂无更多账单
            </div>
          </div>
        </div>

        <!-- 图表区 -->
        <div class="chart-section">
          <!-- 收支趋势图表 -->
          <div class="chart-card">
            <div ref="chartRef" class="chart-container"></div>
          </div>

          <!-- 预算图表 -->
          <div class="chart-card">
            <div ref="budgetChartRef" class="chart-container"></div>
          </div>
        </div>

        <!-- 添加账单弹窗 -->
        <div v-if="showAddModal" class="modal">
          <div class="modal-content">
            <div class="modal-header">
              <h3>添加账单</h3>
              <button class="close-btn" @click="showAddModal = false">&times;</button>
            </div>
            <div class="form-content">
              <div class="form-item">
                <label>支付/收款*</label>
                <select v-model="newBill.type">
                  <option value="0">支出</option>
                  <option value="1">收入</option>
                </select>
              </div>
              <div class="form-item">
                <label>账单类型*</label>
                <template v-if="newBill.type === '0' || newBill.type === 0">
                  <select v-model="newBill.bill_type">
                    <option value="">请选择账单类型</option>
                    <option 
                      v-for="category in budgetCategories" 
                      :key="category.value" 
                      :value="category.value"
                    >
                      {{ category.label }}
                    </option>
                  </select>
                  <input 
                    v-if="showCustomType"
                    type="text" 
                    v-model="customType" 
                    placeholder="请输入其他账单类型"
                    class="custom-input"
                  >
                </template>
                <template v-else-if="newBill.type === '1' || newBill.type === 1">
                  <select v-model="newBill.bill_type">
                    <option value="">请选择收入类型</option>
                    <option 
                      v-for="category in incomeCategories" 
                      :key="category.value" 
                      :value="category.value"
                    >
                      {{ category.label }}
                    </option>
                  </select>
                  <input 
                    v-if="showCustomType"
                    type="text" 
                    v-model="customType" 
                    placeholder="请输入其他收入类型"
                    class="custom-input"
                  >
                </template>
              </div>
              <div class="form-item">
                <label>金额*</label>
                <input 
                  type="number" 
                  v-model="newBill.amount" 
                  placeholder="请输入金额"
                >
              </div>
              <div class="form-item" v-if="newBill.type == '0'">
                <label>支付状态</label>
                <select v-model="newBill.payment_status">
                  <option :value="0">未支付</option>
                  <option :value="1">已支付</option>
                </select>
              </div>
              <div class="form-item">
                <label>{{ newBill.type === '1' ? '收款方式' : '支付方式' }}</label>
                <input 
                  type="text" 
                  v-model="newBill.payment_method" 
                  :placeholder="newBill.type === '1' ? '请输入收款方式' : '请输入支付方式'"
                >
              </div>
              <div class="form-item">
                <label>记录日期</label>
                <input 
                  type="date" 
                  v-model="newBill.due_date"
                >
              </div>
              <div class="form-item">
                <label>备注</label>
                <textarea 
                  v-model="newBill.description" 
                  placeholder="请输入备注信息"
                ></textarea>
              </div>
            </div>
            <div class="modal-footer">
              <button class="cancel-btn" @click="showAddModal = false">取消</button>
              <button class="confirm-btn" @click="handleAddBill">确定</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page-wrapper {
  min-height: 100vh;
  overflow-x: hidden;
  background: #f5f7fa;
}

.page-container {
  display: flex;
  justify-content: center;
  min-height: 100vh;
}

.home-container {
  width: 90%;
  max-width: 1300px;
  padding: 16px;
  box-sizing: border-box;
}

/* 确保所有子元素不会超出容器 */
.user-card,
.statistics-card,
.quick-actions,
.recent-bills,
.chart-card {
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

/* 修改图表容器样式 */
.chart-card {
  margin: 18px 0;
  background: white;
  border-radius: 8px;
  padding: 18px;
  box-sizing: border-box;
}

.chart-container {
  width: 100%;
  height: 350px;
  box-sizing: border-box;
}

/* 修改弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  width: 95%;
  max-width: 450px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
  margin: 20px;
}

/* 修改账单列表样式 */
.bill-list {
  width: 100%;
  box-sizing: border-box;
}

.bill-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 8px;
}

.bill-item:hover {
  background-color: #ddeafa;
}

/* 确保所有输入框不会溢出 */
input, select, textarea {
  max-width: 100%;
  box-sizing: border-box;
}

.user-card {
  background: white;
  border-radius: 8px;
  padding: 18px;
  margin-bottom: 18px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-info h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.statistics-card {
  display: flex;
  gap: 18px;
  margin-bottom: 18px;
}

.stat-item {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 18px;
  text-align: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-item .label {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.stat-item .amount {
  font-size: 22px;
  font-weight: bold;
}

.stat-item.income .amount {
  color: #67c23a;
}

.stat-item.expense .amount {
  color: #f56c6c;
}

.quick-actions {
  margin-bottom: 20px;
}

.action-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 50px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn:hover {
  background: #66b1ff;
}

.action-btn .icon {
  font-size: 24px;
  margin-right: 8px;
}

.recent-bills {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.view-all {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.view-all:hover {
  color: #22b322;
  background-color: #f5f7fa;
}

.loading, .empty {
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.bill-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.bill-info .category {
  font-size: 16px;
  color: #333;
}

.bill-info .date {
  font-size: 12px;
  color: #909399;
}

.bill-item .amount {
  font-size: 18px;
  font-weight: bold;
}

.bill-item .amount.income {
  color: #67c23a;
}

.bill-item .amount.expense {
  color: #f56c6c;
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.close-btn {
  border: none;
  background: none;
  font-size: 20px;
  color: #909399;
  cursor: pointer;
}

.form-content {
  padding: 20px;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-size: 14px;
}

.form-item input,
.form-item select,
.form-item textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.form-item textarea {
  min-height: 80px;
  resize: vertical;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 20px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-btn {
  border: 1px solid #dcdfe6;
  background: white;
  color: #606266;
}

.confirm-btn {
  background: #409eff;
  color: white;
  border: none;
}

.custom-input {
  margin-top: 8px;
}

.no-more{
  text-align: center;
  color: #909399;
  padding: 20px 0;
}

.chart-section {
  display: flex;
  gap: 20px;
}
</style>